//
// Created by FindBin on 2024/5/1.
//

#include "AirCylinder.h"
#include "bsp_can.h"

volatile static uint8_t AirCylinder_state = 0x00;

#define base_id 0x7b0
#define open_port 0xfb
#define close_port 0xbf
/// 1-> 3
/// 4 -> 7
#define FINAL_ID(id) (0xe0 | id)

//void airCylinder_init() {
//    modbus_init();
////    while (!airCylinder_test(0x01)) { HAL_Delay(1000); }
//}

//void airCylinder_open(uint8_t id, AirCylinder_CC airCylinderCc) {
//    AirCylinder_state |= AirCylinder_BIT(airCylinderCc);
//    modbus_transmit_msg1(FINAL_ID(id), CONTROL, AirCylinder_state);
//}

void airCylinder_all_open(FDCAN_HandleTypeDef *hfdcan, uint8_t id) {
    uint8_t send_msg[8] = {0xa4, 0, 0, 0, 0, 0, 0, 0};
    fdcan_send_msg(hfdcan, (base_id | id), 8, send_msg);
}
void airCylinder_all_close(FDCAN_HandleTypeDef *hfdcan, uint8_t id) {
    uint8_t send_msg[8] = {0xa5, 0, 0, 0, 0, 0, 0, 0};
    fdcan_send_msg(hfdcan, (base_id | id), 8, send_msg);
}
void airCylinder_open(FDCAN_HandleTypeDef *hfdcan, uint8_t id,uint8_t port) {
    uint8_t send_msg[8] = {0xa6, open_port, port, 0, 0, 0, 0, 0};
    fdcan_send_msg(hfdcan, (base_id | id), 8, send_msg);
}
void airCylinder_close(FDCAN_HandleTypeDef *hfdcan, uint8_t id,uint8_t port) {
    uint8_t send_msg[8] = {0xa6, close_port, port, 0, 0, 0, 0, 0};
    fdcan_send_msg(hfdcan, (base_id | id), 8, send_msg);
}
//void airCylinder_close(uint8_t id, AirCylinder_CC airCylinderCc) {
//    AirCylinder_state &= (~(AirCylinder_BIT(airCylinderCc)));
//    modbus_transmit_msg1(FINAL_ID(id), CONTROL, AirCylinder_state);
//}



//_Bool airCylinder_test(uint8_t id) {
//    modbus_transmit_msg(FINAL_ID(id), TEST, AirCylinder_TEST_NUB);
//    HAL_UART_Receive(&AirCYLINDER_RS485, AirCYLINDER_RS485_BUFFER, AirCYLINDER_RS485_BUFFER_SIZE, HAL_MAX_DELAY);
//    if (sRxModBusHeader.address == FINAL_ID(id) && sRxModBusHeader.functionCode == TEST &&
//        sRxModBusHeader.data == AirCylinder_TEST_NUB) { return 1; }
//    return 0;
//}

//uint8_t airCylinder_get(uint8_t id) {
//    modbus_transmit_msg(FINAL_ID(id), GET, AirCylinder_GET_NUB);
//    HAL_UART_Receive(&AirCYLINDER_RS485, AirCYLINDER_RS485_BUFFER, AirCYLINDER_RS485_BUFFER_SIZE, HAL_MAX_DELAY);
//    if (sRxModBusHeader.address == FINAL_ID(id) && sRxModBusHeader.functionCode == GET &&
//        modbus_receive_msg(AirCYLINDER_RS485_BUFFER)) { return sRxModBusHeader.data; }
//}

//void airCylinder_cb(_Bool is_continue) {
//
//    HAL_GPIO_TogglePin(LED1_GPIO_Port, LED1_Pin);
//    if (is_continue && sRxModBusHeader.functionCode == RESET_RETRY) {
//        modbus_transmit_msg(sRxModBusHeader.address, CONTROL, AirCylinder_state);
//    }
//}
